<template>
  <div
    class="oss-video-preview"
    :style="{ width: realWidth, height: realHeight }"
  >
    <video
      v-if="realSrc"
      :src="realSrc"
      controls
      :style="{ width: realWidth, height: realHeight, objectFit: 'cover', display: 'block' }"
      @error="handleVideoError"
    >
      您的浏览器不支持 video 标签。
    </video>

    <!-- 错误占位 -->
    <div v-else class="video-slot" :style="{ width: realWidth, height: realHeight }">
      <i class="el-icon-video-camera"></i>
    </div>
  </div>
</template>

<script>
import { isExternal } from "@/utils/validate";

export default {
  name: "OssVideoPreview",
  props: {
    src: {
      type: String,
      default: ""
    },
    width: {
      type: [Number, String],
      default: 200 // 默认 200px
    },
    height: {
      type: [Number, String],
      default: 120 // 默认 120px
    }
  },
  data() {
    return {
      loadError: false
    };
  },
  computed: {
    realSrc() {
      if (!this.src || this.loadError) {
        return "";
      }
      // 取第一个视频地址（兼容中英文逗号）
      let real_src = this.src.split(/[,，]/)[0].trim();
      if (isExternal(real_src)) {
        return real_src;
      }
      return real_src;
    },
    realWidth() {
      return typeof this.width === "string" ? this.width : `${this.width}px`;
    },
    realHeight() {
      return typeof this.height === "string" ? this.height : `${this.height}px`;
    }
  },
  methods: {
    handleVideoError() {
      this.loadError = true;
    }
  }
};
</script>

<style lang="scss" scoped>
.oss-video-preview {
  border-radius: 5px;
  background-color: #000;
  box-shadow: 0 0 5px 1px #ccc;
  overflow: hidden;
  position: relative;

  video {
    display: block;
  }

  .video-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #909399;
    font-size: 30px;
    background-color: #1f1f1f;
  }
}
</style>
